package com.ruoyi.utils;

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.ruoyi.config.StaticResourceConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class FontsUtil {

    private static StaticResourceConfig staticResourceConfig;
    public FontsUtil(){
        this.staticResourceConfig = new StaticResourceConfig();
    }

    private static Map<String, byte[]> fontCache = new HashMap<>();

    private static byte[] loadFontData(String fontPath) {
        return fontCache.computeIfAbsent(fontPath, path -> {
            try {
                ClassPathResource resource = new ClassPathResource(path);
                if (!resource.exists()) {
                    log.error("字体文件不存在: {}", path);
                    return null;
                }
                try (java.io.InputStream inputStream = resource.getInputStream()) {
                    byte[] fontData = org.apache.commons.io.IOUtils.toByteArray(inputStream);
                    log.info("成功加载字体文件: {}, 大小: {} bytes", path, fontData.length);
                    return fontData;
                }
            } catch (Exception e) {
                log.error("加载字体文件失败: {}", path, e);
                return null;
            }
        });
    }

    public static PdfFont getFonts_IDENTITY_H(String path){
        try {
            // 修改字体加载方式 - 使用 ClassPathResource
            byte[] filehb = loadFontData(path);

            PdfFont customFont = PdfFontFactory.createFont(filehb, PdfEncodings.IDENTITY_H);

            return customFont;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] readImageAsBytes(String imagePath) {
        try {
            Path fullPath = getImageFullPath(imagePath);
            String path = fullPath.toAbsolutePath().toString();
            log.info("图片绝对路径："+path);
            if (Files.exists(fullPath) && Files.isReadable(fullPath)) {
                return Files.readAllBytes(fullPath);
            } else {
                log.info("图片文件不存在或不可读: {}", fullPath);
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("读取图片文件失败: {}", imagePath, e);
            return null;
        }
    }

    /**
     * 获取图片的完整路径
     */
    private static Path getImageFullPath(String imagePath) {
        String rootPath = staticResourceConfig.getStaticRootPath();
        log.info("图片根目录："+rootPath);
        Path root = Paths.get(rootPath).toAbsolutePath().normalize();
        Path relativePath = Paths.get(imagePath).normalize();
        // 防止路径遍历攻击
        if (relativePath.startsWith("..") || relativePath.isAbsolute()) {
            throw new SecurityException("非法路径访问: " + imagePath);
        }

        return root.resolve(relativePath);
    }
}
